
/*
*Released on 28th June 2008.
*Any violations can be reported at paritosh@wikiocean.net
*What is treated as violations can be found at www.wikiocean.net/ppl1-voilations*
******************************************************************************
* The contents of this file are subject to POOL Public License 1.0 and later.
* POOL Public License is based on Affero GPL v3 and additional conditions.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the Affero GPL v3 License at http://www.gnu.org/licenses/agpl.html
* You may obtain a copy of the POOL Public License 1.0 or later at www.wikiocean.net/license/ppl.html
* Software distributed under POOL Public License 1.0 is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya (C) 2008. All Rights Reserved.
******************************************************************************
* Objective of the additional terms (license)
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencies.
* 3) To avoid a situation where big corporate or investor can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the freedom is curtailed in companies that get Venture Capital funding.)
******************************************************************************
*/

package  tablization;


import java.util.Hashtable;
import java.util.Vector;

import logger.PoolLogger;

import pool.bean.Master_table_Bean;
import pool.bean.Property_details_Bean;
import utility.ConvertToLower;
import utility.Input;
import control.RequestParameter;
import dbmanager.DBManager;
import dbmanager.GetIdName;
import file.SearchRecord;

/**
 *  @author Shweta
 **/
public class SubTable 
{

	RequestParameter req;	
	Master_table_Bean mtb;
	Property_details_Bean pdb;
	
	GetIdName gin;
	
	SearchRecord sr;
	
	String PID_NAME = "pidName"; //name of table in which searching is to be done
	String keyName = "colName";  //name of key(column) on which searching is to be done
	String valueName = "colValue"; //name of value(column) on which searching is to be done
	
	
	public boolean bool_subTable = false;
	public String [] subArray;
	PoolLogger pl;
	
	public SubTable()
	{
		// logger
		pl = (PoolLogger) PoolLogger.getLogger(this.getClass().getName());
	}
	
	
	/**
	 * this function sets object of DBManager & creates an object of GetIdName classes respectively
	 * @param sqlDB - is an object of DBManager
	 */
	public void initPool()
	{
		gin = new GetIdName();
	}
	
	
	/**
	 * this function is called when new object name is to be inserted in master
	 * @param objectName - contains name of object as string
	 */
	public void callInsertMasterBean(String objectName)
	{
		req = new RequestParameter();
		req.setUsername("+919922930640");
		req.setMessage("System Message");
		req.setPassword("123");	
		
		req.setRequest("master_table");
		req.setProcess("add");	
		
		mtb = new Master_table_Bean();
		
		mtb.setNewHashtable(objectName);
		mtb.initPool();
		mtb.setReqParam(req);
		mtb.insert();	
		
	
	}
	
	
	/**
	 * this function is called when properties are to be inserted in pl
	 * @param propertyVector - contains vector of properties to be inserted in pl
	 */
	@SuppressWarnings("unchecked")
	public void callInsertPropertyBean(Vector<Object> propertyVector)
	{
		req = new RequestParameter();
		req.setUsername("+919922930640");
		req.setMessage("System Message");
		req.setPassword("123");	
		
		req.setRequest("property_details");
		req.setProcess("add");
	
		pdb = new Property_details_Bean();
		pdb.initPool();
		pdb.setReqParam(req);
		
		for(int i=0;i<propertyVector.size();i++)
		{
			Hashtable<Object,Object> propertyHash = (Hashtable<Object, Object>)propertyVector.get(i);
			pdb.setOldPropertyHash(propertyHash);
		}		
		pdb.insert();
		
	}
	
	/**
	 * this function is called when properties are to be updated in pl
	 * @param newPropertyVector - contains vector of new properties to be inserted in pl for existing properties
	 * @param oldPropertyVector - contains vector of old properties to be updated in pl
	 */
	@SuppressWarnings("unchecked")
	public void callUpdatePropertyBean(Vector<Object> newPropertyVector,Vector<Object> oldPropertyVector)
	{
	
		req = new RequestParameter();
		req.setUsername("+919922930640");
		req.setMessage("System Message");
		req.setPassword("123");	
		
		req.setRequest("property_details");
		req.setProcess("mod");
	
		pdb = new Property_details_Bean();
		pdb.initPool();
		pdb.setReqParam(req);
		
		for(int i=0;i<newPropertyVector.size();i++)
		{
			Hashtable<Object,Object> oldPropertyHash = (Hashtable<Object, Object>)oldPropertyVector.get(i);			
			Hashtable<Object,Object> newPropertyHash = (Hashtable<Object, Object>)newPropertyVector.get(i);
			
			pdb.setNewPropertyHash(oldPropertyHash);
			pdb.setNewPropertyHash(newPropertyHash);
		}		
		
		pdb.update();
		
	
	}
	
	/**
	 * this function is called when properties are to be deleted from pl
	 * @param deleteVector - contains vector of properties to be deleted from pl
	 */
	@SuppressWarnings("unchecked")
	public void callDeletePropertyBean(Vector<Object> deleteVector)
	{
		req = new RequestParameter();
		req.setUsername("+919922930640");
		req.setMessage("System Message");
		req.setPassword("123");	
		
		req.setRequest("property_details");
		req.setProcess("del");
		
		pdb = new Property_details_Bean();
		pdb.initPool();
		pdb.setReqParam(req);
		
		for(int i =0;i<deleteVector.size();i++)
		{
			Hashtable<Object,Object> delHash = (Hashtable<Object, Object>)deleteVector.get(i);
			pdb.setOldPropertyHash(delHash);
		}		
		pdb.delete();
		
		
	}
	
	
	/**
	 *  this function creates hashtable in master/pl structure
	 * @param mid - name of object as string
	 * @param pid - property name of object as string
	 * @param pv - property value of property name as string
	 * @return hashtable in master/pl format
	 */
	
	public Hashtable<Object,Object> getMasterHashtable(String mid,String pid,String pv)
	{
		
		Hashtable<Object,Object> hashtable = new Hashtable<Object, Object>();
		
		hashtable.put("mid",mid);
		hashtable.put("pid",pid);
		hashtable.put("pv",pv);
		
		
		return hashtable;
		
	}
		
	
	/**
	 * this function returns value of given column id
	 * @param hashtable contains key-value pair of column-value
	 * @return string containing name of value of given column
	 */
	public String getColumnValue(Hashtable<Object,Object> hashtable)
	{
		
		String strPv = hashtable.get("pv").toString();
		 if(!strPv.equals("0"))
				strPv=gin.getItem(strPv);
			else
				strPv=hashtable.get("vt").toString();		
		 
		
		 return strPv;
	}
	
	
	/**
	 * this function changes master object names given in hashtable into hashtable of master ids
	 * @param propertyHash -hashtable which contains master object names
	 * @return hashtable containing ids of given master names
	 */
	public Hashtable<Object,Object> convertInMasterId(Hashtable<Object,Object> hashtable)
	{
		
		Hashtable<Object,Object> idHash = new Hashtable<Object, Object>();
				
		String tableName = "property_details";
		String process = "add";
		
		idHash.putAll(hashtable);
		idHash = gin.ConvertPVtoVT(idHash);
		idHash = gin.convertMasterId(idHash, tableName,process);
		
		
		return idHash;
	}
	
		
	
	/**
	 * this function returns array of table according to the condition given in hashtable
	 * @param hashtable - contains key-value pair of PID_NAME, keyName & valueName
	 * @return string array of tables 
	 */
	public String [] getArray(Hashtable<Object,Object> hashtable)
	{
		 	String []tableArray;
		 	
		 	String pidName = gin.getId(hashtable.get(PID_NAME).toString());
			String path = Input.MASTERREPORTSPATH + pidName + "//" + pidName + "_pid" + Input.FILRFORMAT;
			 
			 Hashtable<Object,Object> tableHash = new Hashtable<Object, Object>();
			 String value = hashtable.get(valueName).toString();
			 tableHash.put(hashtable.get(keyName),value);
			 
			 sr = new SearchRecord(path);			
			tableArray= sr.getRecordSet(tableHash);				
		
		return tableArray;
	}
	
	
	/**
	 * this function gives name of table for given object respective to given column 
	 * @param tableArray -array of tables belonging to particular object name
	 * @param columnTableArray -array of tables of given column name
	 * @return string containing name of table 
	 */
	public String getTableName(String [] tableArray, String [] columnTableArray)
	{		
	
		int counter = 0;
		
		String tablename ="";				
				
				for(int i=0; i<tableArray.length; i++)
				{
					
					tablename = tableArray[i].split(Input.SEPARATOR)[2];
					for(int j=0; j<columnTableArray.length; j++)
					{
						String tempTablename = columnTableArray[j].split(Input.SEPARATOR)[0];
						if(tempTablename.equals(tablename))
						{
							counter++;
							break;
						}
					}
					if(counter>0)
						break;
				}
				
				tablename = gin.getItem(tablename);	
		return tablename;
		
	}
	
	
	/**
	 * this function checks whether table exists or not for given object name
	 * @param typeObject - name of object for which table is present or not 
	 * @return true if table exists
	 */
	public boolean checkTableExistence(String typeObject)
	{
		
		 String []tableArray;
		boolean flag = false;
		
				Hashtable<Object,Object> arrayHash = new Hashtable<Object, Object>();
				 
					arrayHash.put(PID_NAME, "object");
					arrayHash.put(keyName, "pv");
					arrayHash.put(valueName,gin.getId(typeObject));
						
					subArray=tableArray= getArray(arrayHash);
				
				 if(tableArray.length != 0)
				 {
					 System.out.println("Table exists");
						pl.info("Table exists");
						pl.debug("Table exists");
						pl.warn("Table exists");
						pl.fatal("Table exists");
						pl.error("Table exists");
						pl.trace("Table exists");
					 bool_subTable= true;
				 }
				 else
				 {
					 System.out.println("Table doesnot exist");
						pl.info("Table doesnot exist");
						pl.debug("Table doesnot exist");
						pl.warn("Table doesnot exist");
						pl.fatal("Table doesnot exist");
						pl.error("Table doesnot exist");
						pl.trace("Table doesnot exist");
					 bool_subTable= false;
				 }	
			
				flag = bool_subTable;
		
		return flag;
	}

	/**
	 * this function checks the condition of being unique or multiple-valued table
	 * @param tableName - name of table whose condition is to be checked
	 * @return true if it is multiple-valued table otherwise false
	 */
	@SuppressWarnings("unchecked")
	public boolean checkTableCondition(String tableName)
	{
		
		boolean flag = false;
		 
		String pidName = gin.getId("conditionObject");
		String path = Input.MASTERREPORTSPATH + pidName + "//" + pidName + "_pid" + Input.FILRFORMAT;
		 
		 Hashtable<Object,Object> tableHash = new Hashtable<Object, Object>();
		 tableHash.put("mid",tableName);
		 
		 sr = new SearchRecord(path);			
		 tableHash.putAll(sr.getRecordHash(tableHash));
		 tableHash.putAll(ConvertToLower.convertHashKey(tableHash));
		 
		 String strFlag = gin.getItem(tableHash.get("pv").toString());
		 flag = Boolean.parseBoolean(strFlag);
		
		 System.out.println();
		 System.out.println(flag);
			
		return flag;
	}
	
}
